package controller

import (
	"api_interface/entity"
	"api_interface/service"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 回复评论
func CreateReply() gin.HandlerFunc {
	return func(c *gin.Context) {
		var reply entity.CommentReplyInfo          //用于传给service层的结构体
		if err := c.BindJSON(&reply); err != nil { //将body里的JSON格式数据解构到reply里
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "fail to get json body",
				"data": nil,
			})
			return
		}
		currentTime := time.Now()
		timeString := currentTime.Format("2006-01-02 15:04:05") //定义时间存储样式
		reply.Tim = timeString                                  //将时间赋值给ques.tim
		err := service.CreateReply(&reply)                      //调用service层函数，将reply传给函数用于创建reply
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "fail to create reply",
				"data": nil,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{ //success
			"code": 0,
			"msg":  "success",
			"data": nil,
		})
	}
}

//获取回复

func GetReply() gin.HandlerFunc {
	return func(c *gin.Context) {
		cid1 := c.DefaultQuery("cid", "")
		cid, _ := strconv.Atoi(cid1)
		replies, err := service.GetReply(cid)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "fail to get replies",
				"data": nil,
			})
			return
		}
		reply := *replies
		length := len(reply)
		type ReplyData struct {
			Total   int                       `json:"total"`
			Replies []entity.CommentReplyInfo `json:"replies"`
		}
		data := ReplyData{
			Total:   length,
			Replies: reply,
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": data,
		})
	}
}
